﻿using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using Microsoft.Commerce.Proxy.AccountService;

namespace TestWebApplication.CommerceAccount.APIs
{
    abstract public class CommerceAccountApi : Api
    {
        private const string CommerceContractName = "Microsoft.Commerce.Proxy.AccountService";
        protected AbstractResponse apiResponse;

        public CommerceAccountApi(BasicHttpBinding binding, EndpointAddress address, X509Certificate2 clientCert)
            : base(binding, address, clientCert)
        {
        }

        protected abstract AbstractResponse ExecuteInternal(AccountServiceChannel channel);

        public override void ExecuteCommerceApi()
        {
            using (ChannelFactory<AccountServiceChannel> clientFactory = new ChannelFactory<AccountServiceChannel>(this.binding, this.serviceAddress))
            {
                clientFactory.Endpoint.Contract.Name = CommerceContractName;
                clientFactory.Credentials.ClientCertificate.Certificate = this.certificate;
                AccountServiceChannel channel = clientFactory.CreateChannel();
                
                    this.apiResponse = ExecuteInternal(channel);
                    
                
            }

            switch (this.apiResponse.Ack)
            {
                case AckCodeType.Success:
                    this.response.IsSuccess = true;
                    break;

                case AckCodeType.RetryableFailure:
                    this.response.IsSuccess = false;
                    this.response.NeedRetry = true;
                    this.response.RetryCount++;
                    break;

                case AckCodeType.NonRetryableFailure:
                case AckCodeType.InternalError:
                    this.response.IsSuccess = false;
                    this.response.NeedRetry = false;
                    this.response.RetryCount++;
                    break;
            }
        }
    }
}
